// Package crons
// @Link  https://github.com/bufanyun/hotgo
// @Copyright  Copyright (c) 2023 HotGo CLI
// @Author  Ms <133814250@qq.com>
// @License  https://github.com/bufanyun/hotgo/blob/master/LICENSE
package crons

import (
	"context"
	"encoding/json"
	"fmt"
	"hotgo/internal/library/cron"
	"hotgo/internal/model/entity"
	"hotgo/internal/model/input/sysin"
	"hotgo/internal/service"
	"io"
	"net/http"
	"net/url"
	"slices"
)

func init() {
	cron.Register(SpotIndex)
}

// SpotIndex 测试任务（无参数）
var SpotIndex = &cSpotIndex{name: "spot_index"}
var stockZhASpotIndex = "http://127.0.0.1:8000/api/public/stock_zh_index_spot_em"

type stockZhASpotIndexResp struct {
	Code            string  `json:"代码"                 `
	Name            string  `json:"名称"                 `
	LastPrice       float64 `json:"最新价"            `
	ChangePercent   float64 `json:"涨跌幅"        `
	ChangeAmount    float64 `json:"涨跌额"         `
	Volume          float64 `json:"成交量"               `
	Turnover        float64 `json:"成交额"             `
	Amplitude       float64 `json:"振幅"            `
	High            float64 `json:"最高"                 `
	Low             float64 `json:"最低"                  `
	Open            float64 `json:"今开"                 `
	Closed          float64 `json:"昨收"               `
	VolumeRatio     float64 `json:"量比"               `
	YesterdayClosed float64 `json:"流通市值" `
}
type cSpotIndex struct {
	name string
}

func (c *cSpotIndex) GetName() string {
	return c.name
}

// Execute 执行任务
func (c *cSpotIndex) Execute(ctx context.Context, parser *cron.Parser) (err error) {
	//proxyURL, _ := url.Parse("http://localhost:8888")
	//http.DefaultTransport.(*http.Transport).Proxy = http.ProxyURL(proxyURL)

	response, err := http.Get(fmt.Sprintf("%s?symbol=%s", stockZhASpotIndex, url.QueryEscape("指数成份")))
	if err != nil {
		parser.Logger.Warning(ctx, "cron CloseOrder Execute http.Get err:%+v", err)
		return
	}
	defer response.Body.Close()
	body, err := io.ReadAll(response.Body)
	if err != nil {
		parser.Logger.Warning(ctx, "cron CloseOrder Execute io.ReadAll err:%+v", err)
		return err
	}
	var resp []stockZhASpotIndexResp
	err = json.Unmarshal(body, &resp)
	if err != nil {
		parser.Logger.Warning(ctx, "cron CloseOrder Execute json.Unmarshal err:%+v", err)
		return err
	}
	indexSclice := []string{"深证成指", "创业板指", "上证指数", "上证50", "沪深300"}
	for _, emResp := range resp {
		if !slices.Contains(indexSclice, emResp.Name) {
			continue
		}
		err := service.SysStockZhAIndex().Edit(ctx, &sysin.StockZhAIndexEditInp{
			StockZhAIndex: entity.StockZhAIndex{
				Code:            emResp.Code,
				Name:            emResp.Name,
				LastPrice:       emResp.LastPrice,
				ChangePercent:   emResp.ChangePercent,
				ChangeAmount:    emResp.ChangeAmount,
				Volume:          emResp.Volume,
				Turnover:        emResp.Turnover,
				Amplitude:       emResp.Amplitude,
				High:            emResp.High,
				Low:             emResp.Low,
				Open:            emResp.Open,
				Closed:          emResp.Closed,
				VolumeRatio:     emResp.VolumeRatio,
				YesterdayClosed: emResp.YesterdayClosed,
			},
		})
		if err != nil {
			parser.Logger.Warning(ctx, "cron CloseOrder Execute service.SysstockZhASpotIndex().Edit err:%+v", err)
			continue
		}
	}
	return
}
